package com.dng.book.service.impl;

import com.dng.book.service.SmsService;
import com.dng.book.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 短信服务实现类
 * 
 * @author dng
 * @since 2024-01-01
 */
@Slf4j
@Service
public class SmsServiceImpl implements SmsService {
    
    @Resource
    private RedisUtil redisUtil;
    
    private static final String SMS_CODE_PREFIX = "sms:";
    private static final int SMS_CODE_EXPIRE = 300; // 5分钟过期
    private static final int SMS_CODE_LENGTH = 4;
    
    @Override
    public boolean sendSmsCode(String phone) {
        try {
            // 生成4位数字验证码 (0000-9999)
            String code = generateSmsCode();
            String redisKey = SMS_CODE_PREFIX + phone;
            
            // 存储到Redis，5分钟过期
            redisUtil.set(redisKey, code, SMS_CODE_EXPIRE, TimeUnit.SECONDS);
            
            log.info("发送短信验证码: phone={}, code={}", phone, code);
            
            // 这里应该调用真实的短信服务
            // 目前只是模拟发送成功
            return true;
        } catch (Exception e) {
            log.error("发送短信验证码失败: phone={}", phone, e);
            return false;
        }
    }
    
    @Override
    public boolean verifySmsCode(String phone, String code) {
        try {
            String redisKey = SMS_CODE_PREFIX + phone;
            String storedCode = redisUtil.get(redisKey);
            
            log.info("验证短信验证码: phone={}, 用户输入={}, redis中={}", phone, code, storedCode);
            
            if (storedCode == null) {
                log.warn("短信验证码不存在或已过期: phone={}", phone);
                return false;
            }
            
            boolean isValid = storedCode.equals(code);
            if (isValid) {
                log.info("短信验证码验证成功: phone={}", phone);
                // 验证成功后删除验证码
                deleteSmsCode(phone);
            } else {
                log.warn("短信验证码验证失败: phone={}, 用户输入={}, 正确码={}", phone, code, storedCode);
            }
            
            return isValid;
        } catch (Exception e) {
            log.error("验证短信验证码异常: phone={}", phone, e);
            return false;
        }
    }
    
    @Override
    public void deleteSmsCode(String phone) {
        try {
            String redisKey = SMS_CODE_PREFIX + phone;
            redisUtil.delete(redisKey);
            log.info("删除短信验证码: phone={}", phone);
        } catch (Exception e) {
            log.error("删除短信验证码失败: phone={}", phone, e);
        }
    }
    
    /**
     * 生成4位数字验证码 (0000-9999)
     * 
     * @return 验证码
     */
    private String generateSmsCode() {
        Random random = new Random();
        int code = random.nextInt(10000); // 0-9999
        return String.format("%04d", code); // 补齐4位，如 0001, 0123, 9999
    }
} 